<template>
	<view>
		<view class="wanl-search">
			<!-- 导航条 -->
			<view class="cu-custom" :style="{height: $wanlshop.wanlsys().height + 'px' }">
				<view class="cu-bar fixed"
					:style="{ height: $wanlshop.wanlsys().height + 'px', paddingTop: $wanlshop.wanlsys().top + 'px'}">
					<view class="action" @tap="$wanlshop.back(1)">
						<text class="wlIcon-fanhui1"></text>
					</view>
					<view class="search-form round">
						<text class="wlIcon-sousuo1 text-bold"></text>
						<input type="text" maxlength="12" confirm-type="search" placeholder-style="color: #ccc"
							:placeholder="searchKeywords ? searchKeywords : `搜索 ${searchTypeText[searchType]}`"
							@confirm="onSearchInputConfirmed" @input="onSearchInputChanged" focus />
					</view>
				</view>
			</view>

			<view class="wanl-list">
				<view class="head" style="margin-top:5px;">
					<view class="cue">

						<view class="bar" style="background-color: #fff;">
							<view class="item " :class="{ text_linear: filterIndex === 0 }" @tap="tabClick(0,'商品')">商品
							</view>
							<view class="item " :class="{ text_linear: filterIndex === 1 }" @tap="tabClick(1,'会员秀')">会员秀
							</view>
							<view class="item " :class="{ text_linear: filterIndex === 2 }" @tap="tabClick(2,'资讯')">资讯
							</view>
							<!-- <view class="item" :class="{ current: filterIndex === 3 }" @tap="tabClick(3)">
							<text>价格</text>
							<view class="box">
								<text :class="{ active: priceOrder === 1 && filterIndex === 3 }" class="wlIcon-sheng"></text>
								<text :class="{ active: priceOrder === 2 && filterIndex === 3 }" class="wlIcon-jiang"></text>
							</view>
						</view>
						<view class="item" @tap="showDrawer()">
							筛选
							<text class="wlIcon-shaixuan margin-left-xs "></text>
						</view> -->
						</view>
					</view>
				</view>

				<view class="history padding-lr" v-if="isHistory">
					<view v-if="historyList.length > 0">
						<view class="title">
							<text>历史搜索</text>
							<text class="wlIcon-lajitong" @tap="removeHistory"></text>
						</view>
						<view class="list">
							<view v-for="(item, index) in historyList" :key="item.keywords"
								@tap="keywordsToList(item.keywords)">{{ item.keywords }}</view>
						</view>
					</view>
					<view>
						<view class="title">
							<text>热门搜索</text>
							<text class="wlIcon-guanzhu"></text>
						</view>
						<view class="list">
							<block v-for="(item, index) in searchList" :key="item.id">
								<view v-if="item.flag == 'hot'" class="action" @tap="keywordsToList(item.title)">
									<text>{{ item.title }}</text>
									<text class="cu-tag badge">hot</text>
								</view>
								<view @tap="keywordsToList(item.title)" v-else>
									<text>{{ item.title }}</text>
								</view>
							</block>
						</view>
					</view>
				</view>
				<view class="cu-list menu" v-else>
					<view class="cu-item" v-for="(item, index) in search.searchList" :key="item.keywords">
						<view class="content" @tap="keywordsToList(item.keywords)">
							<text class="text-sm">{{ item.keywords }}</text>
						</view>
					</view>
					<view class="cu-item arrow" v-for="(item, index) in search.categoryList" :key="item.id"
						@tap="categoryToList(item.id, item.name)" v-if="searchType !== 'find'">
						<view class="content">
							<text class="text-sm text-gray">{{ item.name }}</text>
						</view>
						<view class="action">
							<view class="cu-tag round bg-orange light">{{ item.name }}类目</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 主体 -->

			<block v-if="filterIndex === 0">
				<!-- {{goodsData}} -->
				<wanl-product :dataList="goodsData" :dataStyle="liststyle" :dataType="goodsType" />
			</block>

			<block v-if="filterIndex === 1">

				<div class="list">
					<div class="list-item" v-for="(item, index) in newsData" :key="index">
						<!-- <div class="user-info">
							<div class="pic">
								<image :src="item.avatar" mode="scaleToFill" />
							</div>
							<div class="flex-col">
								<div style="color: #2e2e2e;">{{ item.nickname }}</div>
								<div class="dot">
									⭐️⭐️⭐️
								</div>
							</div>
						</div> -->
						<div style="color: #4d4d4d;" class="title">{{ item.title }}</div>
						<div style="color: #808080;" class="title">{{ item.content }}</div>
						<div class="image-list">
							<image v-for="(v, i) in item.img" :key="i" :src="v" mode="scaleToFill" />
						</div>
						<div class="remark" v-if="item.remark">{{ item.remark}}</div>
						<!-- <div class="tips">
						{{item.good_name}}
						<image src="" mode="scaleToFill" />
					</div> -->
					</div>
				</div>
			</block>
			<block v-if="filterIndex === 2">
				<!-- {{goodsData}} -->
				<div class="list">
					<div class="list-item" v-for="(item, index) in newsData" :key="index">
						<!-- <div class="user-info">
						<div class="pic">
							<image :src="item.avatar" mode="scaleToFill" />
						</div>
						<div class="flex-col">
							<div style="color: #2e2e2e;">{{ item.nickname }}</div>
							<div class="dot">
								⭐️⭐️⭐️
							</div>
						</div>
					</div> -->
						<div style="color: #4d4d4d;" class="title">{{ item.create_time }}</div>
						<div style="color: #808080;" class="title">{{ item.content }}</div>
						<div class="image-list">
							<image v-for="(v, i) in item.img" :key="i" :src="v" mode="scaleToFill" />
						</div>
						<div class="remark" v-if="item.remark">{{ item.remark}}</div>
						<!-- <div class="tips">
						{{item.good_name}}
						<image src="" mode="scaleToFill" />
					</div> -->
					</div>
				</div>
			</block>
		</view>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				flag: 'new',
				page: 1,
				is_search: false,
				keywords: '',
				hot_keywords: [],
				history_keywords: [],
				search_keywords: [],
				sign_name: '',
				good_sign: '',
				WanlScroll: 0, //记录页面滚动
				scrollStype: false, //滚动状态
				filterIndex: 0, //
				priceOrder: 0, //1 价格从低到高 2价格从高到低
				liststyle: 'col-1-10', //列表样式
				goodsData: [], //商品列表数据
				newsData: [],
				showRight: false,
				category: '',
				goodsType: 'goods',
				empty: '没有找到任何宝贝',
				params: {
					search: '',
					sort: 'weigh',
					order: 'asc',
					page: 1,
					filter: {},
					op: {}
				},
				reload: false, //判断是否上拉
				last_page: 0,
				status: 'loading',
				contentText: {
					contentdown: '',
					contentrefresh: '正在加载..',
					contentnomore: '没有更多数据了'
				},
				searchType: 'goods',
				searchTypeText: {
					goods: '商品',
					groups: '资讯',
					find: '会员秀'
				},
				searchKeywords: '',
				isHistory: true, //历史记录&实时搜索
				searchList: {}, //热门搜索列表
				historyList: [], //历史记录列表
				search: {
					categoryList: {},
					searchList: {}
				}
			};
		},
		onReady() {
			this.loadData();
			this.historyList = uni.getStorageSync('search:history');
		},
		onLoad(option) {
			if (option.keywords) this.searchKeywords = option.keywords;
			if (option.type) this.searchType = option.type;

			this.goodsList();
			this.getList();
		},
		// 监听上拉
		onPullDownRefresh() {
			this.params.page = 1;
			this.reload = true;
			this.goodsList();
		},
		// 下拉刷新
		onReachBottom() {
			if (this.params.page >= this.last_page) {
				this.status = 'noMore';
			} else {
				this.reload = false;
				this.contentText.contentdown = '上拉显示更多';
				this.params.page = this.params.page + 1; //页码+1
				this.status = 'loading';
				this.goodsList();
			}
		},
		// 监听滚动
		onPageScroll(object) {
			if (object.scrollTop > this.WanlScroll) {
				this.scrollStype = false;
			} else {
				this.scrollStype = true;
			}
			if (object.scrollTop < 0) {
				this.scrollStype = false;
			}
			this.WanlScroll = object.scrollTop;
		},
		// 监听返回
		onUnload() {
			if (this.showRight) {
				this.closeDrawer();
				return true;
			}
		},
		methods: {
			//筛选点击
			tabClick(index, sign_name) {

				this.filterIndex = index;
				this.status = 'loading';
				this.params.page = 1;
				this.params.sign = sign_name;

				this.reload = true;
				this.loadData();
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				});
			},
			async searchList_init() {

				await uni.request({
					url: `/api/search/searchList`,
					data: {
						token: uni.getStorageSync("wanlshop:user").token,
						flag: 'good',
						title: this.keywords,
						page: this.page,
						region_name: uni.getStorageSync("city_name"),
					},
					success: res => {
						console.log(res.data)

						this.page = 1;
						this.loadmore = true;
						this.goodsData = [];
						this.goodsList();

					}
				});
			},
			async getList() {
				this.params.cat_id = this.cat_id;
				this.params.flag = "new";
				await uni.request({
					url: "/api/Xiaoyouquan/xyqList",
					data: this.params,
					success: (res) => {
						uni.stopPullDownRefresh();
						this.status = "more";
						if (res.data.length < 10) {
							this.status = 'noMore'
						}
						if (res.data.length >= 10) {
							this.reload = true
							this.newsData = res.data;
						} else {
							this.newsData = this.newsData.concat(res.data);
						}
						if (res.data.length == 0) {
							this.empty = `没找到与“${this.category}${this.params.search}"相关的宝贝`;
						}
						// this.params.page = res.data.current_page; //当前页码
						// this.last_page = res.data.last_page; //总页码
					},
				});
			},
			async goodsList() {
				let that = this;
				await uni.request({
					url: `/api/search/searchList`,
					data: {
						token: uni.getStorageSync("wanlshop:user").token,
						flag: 'good',
						title: this.keywords,
						page: this.page,
						region_name: uni.getStorageSync("city_name"),
					},
					success: res => {
						console.log(res.data)

						// if (res.data.list.length < 20) {
						// 	this.loadmore = false
						// }
						res.data.list.forEach(function(el) {
							that.goodsData.push(el)
						})

					}
				});
			},
			async loadData() {
				await uni.request({
					url: '/api/search/searchKey',
					success: res => {
						this.searchList = res.data;
					}
				});
			},
			async loadSearch(val) {
				await uni.request({
					url: '/api/search/searchKey',
					data: {
						search: val
					},
					success: res => {
						this.search = res.data;
						if (res.data.searchList.length != 0) {
							this.isHistory = false
						}
					}
				});
			},
			async setSearch(text) {
				await uni.request({
					url: '/api/search/setSearch',
					data: {
						keywords: text
					}
				});
			},
			// 存储历史数据
			setHistory(text) {
				// this.setSearch(text);
				this.loadData(); //重新加载热门搜索
				let historyList = uni.getStorageSync('search:history');
				this.historyList = [];
				this.historyList = historyList; //重新加载历史记录
				let searchHistory = historyList;
				if (!searchHistory) searchHistory = [];
				let serachData = {};
				if (typeof text === 'string') {
					serachData = {
						keywords: text
					};
				} else {
					serachData = text;
				}
				// 判断数组是否存在，如果存在，那么将放到最前面
				for (var i = 0; i < searchHistory.length; i++) {
					if (searchHistory[i].keywords === serachData.keywords) {
						searchHistory.splice(i, 1);
						break;
					}
				}
				searchHistory.unshift(serachData);
				uni.setStorage({
					key: 'search:history',
					data: searchHistory
				});
			},
			// 清空历史数据
			removeHistory() {
				uni.showModal({
					title: '提示',
					content: '是否清理全部搜索历史？该操作不可逆。',
					success: res => {
						if (res.confirm) {
							this.historyList = [];
							uni.removeStorage({
								key: 'search:history'
							});
						}
					}
				});
			},
			// 跳转列表
			keywordsToList(keywords) {
				this.setHistory(keywords);
				this.keywords = keywords;
				this.searchList_init();
				// if (this.searchType === 'find') {
				// 	this.$wanlshop.to(`/pages/apps/find/list?search=${keywords}`);
				// } else {
				// 	this.$wanlshop.to(`/pages/product/list?type=${this.searchType}&search=${keywords}`);
				// }
			},
			categoryToList(category_id, category_name) {
				this.setHistory(category_name);
				this.$wanlshop.to(
					`/pages/product/list?type=${this.searchType}&data=${JSON.stringify({ category_id: category_id, category_name: category_name })}`
				);
			},
			onSearchInputChanged(event) {
				let value = event.detail.value;
				if (!value) {
					this.isHistory = true;
					return;
				} else {
					this.loadSearch(value);
				}
			},
			onSearchInputConfirmed(event) {
				let value = event.detail.value;
				if (!value) {
					this.isHistory = true;
					if (this.searchKeywords) {
						this.keywordsToList(this.searchKeywords);
					} else {
						uni.showModal({
							title: '提示',
							content: '请输入内容。'
						});
						return;
					}
				} else {
					this.isHistory = true;
					uni.hideKeyboard();
					this.historyList = [];
					this.historyList = uni.getStorageSync('search:history');
					this.keywordsToList(value); //跳转列表页面
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.text_linear {
		font-weight: bolder;
		display: inline-block;
		height: 100%;
		/*color: #72D5EF;  颜色改不了*/
		font-size: .75rem;
		font-family: PingFangSC-Medium;
		font-weight: 500;
		color: #005A93 !important;
		padding: 0 .2rem;
		border-bottom: .1rem solid #005A93;
		/* background:rgba(239,249,255,0.4); */
	}

	.tag-keyword {
		font-size: 0.75rem !important;
		font-weight: 400 !important;
		padding: 0.3rem 0.75rem;
		border-radius: 0.4rem;
		background-color: #F6F6F6 !important;
		color: #333333;
		margin-bottom: 0.5rem;
		display: inline-block;
		margin-right: 0.7rem;
		position: relative;
	}

	.list {
		padding: 20rpx;
		box-sizing: border-box;

		&-item {
			background: #fff;
			padding: 20rpx;
			box-sizing: border-box;
			margin-top: 20rpx;

			.user-info {
				display: flex;
				align-items: center;
				width: 100%;
				height: 100%;
				position: relative;

				.flex-col {
					display: flex;
					flex-direction: column;
					justify-content: space-between;
				}

				.pic {
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
					background: #214a75;
					margin-right: 20rpx;
					overflow: hidden;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.dot {
					position: absolute;
					top: 50%;
					right: 20rpx;
					transform: translateY(-50%);
					display: flex;
					align-items: center;

					&-item {
						width: 10rpx;
						height: 10rpx;
						border-radius: 50%;
						margin-right: 10rpx;
						background: #999;
					}
				}
			}

			.remark {
				margin-top: 20rpx;
				background: #f5f5f5;
				color: #808080;
				padding: 20rpx;
				box-sizing: border-box;
				border-radius: 20rpx;
			}

			.title {
				margin-top: 30rpx;
			}

			.image-list {
				display: flex;
				padding: 20rpx 0;
				box-sizing: border-box;
				border-bottom: 1rpx solid #eee;

				image {
					width: 210rpx;
					height: 210rpx;
					margin-right: 20rpx;
				}
			}

			.tips {
				background: #f2f7fa;
				font-size: 26rpx;
				color: #005a93;
				height: 80rpx;
				padding: 20rpx;
				box-sizing: border-box;
				border-radius: 20rpx;
				margin-top: 20rpx;
				position: relative;

				image {
					position: absolute;
					right: 20rpx;
					top: 50%;
					transform: translateY(-50%);
				}
			}

			.icon {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;

				&-item {
					image {
						width: 34rpx;
						height: 34rpx;
						margin-right: 20rpx;
					}
				}
			}
		}
	}


	page {
		background: #ffffff;
	}

	.cu-custom .search-form {
		border: 3rpx solid #fe6600;
		background-color: #fff;
	}
</style>